package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;


    @Around("@annotation(com.itheima.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1.操作人ID
        // 获取请求头中的token，拿到jwt令牌
        String jwt = request.getHeader("token");

        // 解析令牌
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");

        // 2.操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        // 3.操作类名
        String className = joinPoint.getTarget().getClass().getName();

        // 4.操作的方法名
        String methodName = joinPoint.getSignature().getName();

        // 5.操作的方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = JSONObject.toJSONString(args);

        // 6.操作方法的返回值
        long begin = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();

        String returnValue = JSONObject.toJSONString(result);

        // 7.操作耗时
        long costTime = end - begin;

        OperateLog log = new OperateLog(null, operateUser, operateTime, className,
                methodName, methodParams, returnValue, costTime);

        operateLogMapper.insert(log);

        // 8.返回原始方法运行的结果
        return result;
    }
}
